package idiolect.webstorage;

import idiolect.core.Topic;
import idiolect.core.TopicEditorDialog;
import idiolect.helpers.Worker;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.ArrayList;
import java.util.concurrent.*;

public class WebStorageDialog extends JDialog implements ActionListener {
    private JPanel contentPane;
    private java.util.List<TopicInfo> list = new CopyOnWriteArrayList<TopicInfo>();
    private JTable table;
    private TopicInfoTableModel model;

    public WebStorageDialog(JFrame owner) {
        super(owner, "Web Storage Browser", ModalityType.MODELESS);
        setContentPane(contentPane = new JPanel());
        setSize(700, 400);
        setVisible(true);
        showLoadingProgress();
    }

    private void showLoadingProgress() {
        contentPane.setLayout(new GridLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        JProgressBar bar = new JProgressBar();
        bar.setString("Loading...");
        bar.setIndeterminate(true);
        contentPane.add(bar, gbc);
        final Future<java.util.List<TopicInfo>> future = Worker.getInstance().submit(TopicListTask.getInstance());
        Worker.getInstance().addTask(new Runnable() {
            public void run() {
                try {
                    final java.util.List<TopicInfo> infos = future.get(20, TimeUnit.SECONDS);
                    if (infos != null) {
                        list.clear();
                        list = infos;
                    }
                    SwingUtilities.invokeLater(new Runnable() {
                        public void run() {
                            showTable();
                        }
                    });
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (ExecutionException e) {
                    e.printStackTrace();
                } catch (TimeoutException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void showTable() {
        model = new TopicInfoTableModel(list);
        table = new JTable(model);
//        for (int i = 0; i < TopicInfoTableModel.COLUMNS.length; i++) {
//            String column = TopicInfoTableModel.COLUMNS[i];
//            table.getColumn(column).setPreferredWidth();
//        }
        contentPane.removeAll();
        contentPane.setLayout(new BorderLayout());
        contentPane.add(new JScrollPane(table, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER), BorderLayout.CENTER);
        JButton downloadButton = new JButton("Download & Open Selected Dictionaries");
        downloadButton.addActionListener(this);
        contentPane.add(downloadButton, BorderLayout.SOUTH);
        contentPane.invalidate();
        contentPane.revalidate();
        contentPane.repaint();
    }

    public void actionPerformed(ActionEvent e) {
        int[] rows = table.getSelectedRows();
        java.util.List<TopicInfo> selection = new ArrayList<TopicInfo>();
        for (int row : rows) {
            TopicInfo info = model.getTopicInfo(row);
            if (info != null)
                selection.add(info);
        }
        for (TopicInfo info : selection) {
            download(info);
        }
    }

    private void download(TopicInfo info) {
        final Future<File> f1 = Worker.getInstance().submit(new TopicDownloadTask(info));
        Worker.getInstance().addTask(new Runnable() {
            public void run() {
                try {
                    final File file = f1.get(20, TimeUnit.SECONDS);
                    if (file != null) {
                        final Future<Topic> future = Topic.load(file);
                        SwingUtilities.invokeLater(new Runnable() {
                            public void run() {
                                try {
                                    Topic topic = future.get(15, TimeUnit.SECONDS);
                                    if (topic != null)
                                        new TopicEditorDialog((JFrame) WebStorageDialog.this.getOwner(), topic).setVisible(true);
                                } catch (InterruptedException e1) {
                                    e1.printStackTrace();
                                } catch (ExecutionException e1) {
                                    e1.printStackTrace();
                                } catch (TimeoutException e1) {
                                    e1.printStackTrace();
                                }

                            }
                        });
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (ExecutionException e) {
                    e.printStackTrace();
                } catch (TimeoutException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}
